﻿using System.ComponentModel;
using System.Reflection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using UAParser;

namespace Core.Extensions;

public static class EndpointExtensions
{
    /// <summary>
    /// 获取当前请求对应的控制器描述、方法描述和完整路由
    /// </summary>
    public static (
        string? ControllerDescription,
        string? ActionDescription,
        string? RouteTemplate,
        string? HttpMethod,
        string? OperatingSystem, 
        string? BrowserType )
        GetControllerActionInfo(this HttpContext httpContext)
    {
        var endpoint = httpContext.GetEndpoint();
        if (endpoint == null) return (null, null, null, null, null, null);

        // 从 Endpoint 获取 ControllerActionDescriptor
        var controllerActionDescriptor = endpoint.Metadata.GetMetadata<ControllerActionDescriptor>();
        if (controllerActionDescriptor == null) return (null, null, null, null, null, null);

        // 控制器类型信息
        var controllerType = controllerActionDescriptor.ControllerTypeInfo;
        var methodInfo = controllerActionDescriptor.MethodInfo;

        // 获取 [Description] 特性
        var controllerDescAttr = controllerType.GetCustomAttribute<DescriptionAttribute>();
        var actionDescAttr = methodInfo.GetCustomAttribute<DescriptionAttribute>();

        string controllerDescription = controllerDescAttr?.Description ?? controllerType.Name;
        string actionDescription = actionDescAttr?.Description ?? methodInfo.Name;

        // 获取完整路由（包括 ControllerRoute + ActionRoute）
        string? routeTemplate = controllerActionDescriptor.AttributeRouteInfo?.Template;

        // 如果没有定义显式路由，则尝试拼接默认模板
        if (string.IsNullOrWhiteSpace(routeTemplate))
        {
            string controllerRoute = controllerActionDescriptor.ControllerName;
            string actionRoute = controllerActionDescriptor.ActionName;
            routeTemplate = $"/api/{controllerRoute}/{actionRoute}";
        }
        else
        {
            // 标准化路径，加上前缀 `/`
            if (!routeTemplate.StartsWith("/"))
                routeTemplate = "/" + routeTemplate;
        }

        // 获取HTTP方法
        string httpMethod = httpContext.Request.Method;

        string? os = null;
        string? browser = null;
        var userAgent = httpContext.Request.Headers.UserAgent.ToString();
        if (!string.IsNullOrEmpty(userAgent))
        {
            var uaParser = Parser.GetDefault();
            var clientInfo = uaParser.Parse(userAgent);
            os = clientInfo.OS.Family;      // 如 "Windows", "Android"
            browser = clientInfo.UA.Family; // 如 "Chrome", "Safari"
        }

        return (controllerDescription, actionDescription, routeTemplate, httpMethod, os, browser);
    }
}
